package net.love5z.web.common.utils;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class ServletUtils {

    private static final Logger logger = Logger.getLogger(ServletUtils.class);

    /**
     * 
     * @param request
     * @return
     */
    public static String getBaseUrl(HttpServletRequest request) {
        if (logger.isDebugEnabled()) {
            for (@SuppressWarnings("unchecked")
            Enumeration<String> headerNames = request.getHeaderNames(); headerNames
                .hasMoreElements();) {
                String headerName = headerNames.nextElement();
                for (@SuppressWarnings("unchecked")
                Enumeration<String> headers = request.getHeaders(headerName); headers
                    .hasMoreElements();) {
                    logger.debug(headerName + " : " + headers.nextElement());
                }
            }
        }

        StringBuilder url = new StringBuilder();
        String schema = request.getScheme();
        String serverName = request.getServerName();
        int port = request.getServerPort();
        String contextPath = request.getContextPath();
        url.append(schema);
        url.append("://");
        url.append(serverName);

        if ((StringUtils.equalsIgnoreCase("http", schema) && port != 80)
            || (StringUtils.equalsIgnoreCase("https", schema) && port != 443)) {
            url.append(":");
            url.append(port);
        }

        url.append(contextPath);

        if (logger.isDebugEnabled()) {
            logger.debug("schema: " + schema);
            logger.debug("serverName: " + serverName);
            logger.debug("port: " + port);
            logger.debug("contextPath: " + contextPath);
            logger.debug("remote: " + request.getRemoteAddr() + ", " + request.getRemoteHost()
                         + ", " + request.getRemotePort());
        }
        return url.toString();
    }
}
